<template>
  <div class="tableInfo">
    <el-table :data="tableData" height="250" style="width: 100%">
      <template v-for="item in labelList" :key="item.prop">
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :min-width="item.minWidth"
          :align="item.align"
          header-align
          :fixed="item.fixed"
        >
          <template v-if="!item.solt" #default="scoped">
            <template v-if="item.type === 'input' || !item.type">
              <el-input
                v-model="scoped.row[item.prop]"
                :placeholder="item.placeholder ? item.placeholder : item.label"
                :disabled="item.disabled"
              ></el-input>
            </template>
            <template v-if="item.type === 'select'">
              <el-select
                v-model="scoped.row[item.prop]"
                :placeholder="item.label"
                :disabled="item.disabled"
              >
                <el-option
                  v-for="item in item.options"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </template>
          <template v-else #default="scoped">
            <slot
              :name="item.solt"
              :scopedRow="scoped.row"
              :deleteRow="() => deleteRow(scoped.$index)"
            >
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div class="border" @click="addRow" v-if="pageType !== 'detail'">
      <el-icon size="30px" color="#e2d6d6"><Plus /></el-icon>
    </div>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance()
const props = defineProps({
  labelList: {
    type: Array,
    default: () => []
  },
  dataList: {
    type: Array,
    default: () => []
  },
  pageType: {
    type: String,
    default: 'add'
  }
})

const tableData = ref([])
watch(
  () => props.dataList,
  newVal => {
    if (newVal.length > 0) {
      tableData.value = newVal
    }
  },
  {
    deep: true,
    immediate: true
  }
)

function addRow() {
  const obj = {}
  props.labelList.forEach(item => {
    obj[item.prop] = null
  })
  tableData.value.push(obj)
}

function deleteRow(index) {
  proxy.$modal.confirm('是否删除该行数据?').then(() => {
    tableData.value.splice(index, 1)
    proxy.$forceUpdate()
  })
}

function exportData() {
  return tableData.value
}

defineExpose({
  exportData
})
</script>

<style scoped lang="scss">
.border {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ebeef5;
  border-top: none;
  cursor: pointer;
}
</style>
